# !/usr/bin python3                                
# encoding: utf-8 -*-
# @file: ant_pool.py                       
# @author   : wjd
# @Time: 2024/4/2 15:30

"""
@Desc: 封装http请求（对接AntalPool集团账户需求）
@Author: liuyufei
@Date: 2024/01/17
"""

import base64
import json
import random
import requests
import string
import time
import urllib
import urllib3
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5


class OpenApiHttpRequest(object):

    def __init__(self, host, api_key, private_key):
        """
        :param host:
        :param api_key:
        :param private_key:
        """
        self.host = host
        self.private_key = private_key
        self.headers = {
            "content-type": "application/json",
            "Accept-Language": "zh-CN",
            "API-Key": api_key,
        }
        urllib3.disable_warnings()

    def get_signature(self, method, api_path, nonce, timestamp, body):
        """
        Desc：使用 RSA私钥 SHA1WithRSA生成签名
        :param method: "GET" "POST"
        :param api_path: 接口地址，比如"/api/cloud/user/add"
        :param nonce: 8位随机字符串
        :param timestamp: 当前时间的13位时间戳
        :param body: 请求体
        :return: "oKRvW/CiyfWbFn7q+L246NKu0sjUK1o9vt6ZfzzahJUPH2SE69VV9e2iLl9mlNDaUHSPef5GTGzwOoqzGRvKMw=="
        """
        # 初始化签名对象（需要使用私钥）
        signer = PKCS1_v1_5.new(RSA.importKey(self.private_key))
        # 签名前准备的数据，HTTP_METHOD + | + HTTP_REQUEST_PATH +  | + NONCE + | + TIMESTAMP + | + BODY
        digest = SHA1.new("|".join([method, api_path, nonce, timestamp, body]).encode())
        # 使用私钥对数据生成 RSA 签名
        print("签名前准备的数据：", "|".join([method, api_path, nonce, timestamp, body]))
        signature = base64.b64encode(signer.sign(digest))
        print("签名结果：", signature.decode())
        return signature.decode()

    def add_headers_info(self, method, path, params):
        """
        Desc：添加签名信息到请求头
        :param method: "GET" "POST"
        :param path: 接口地址，比如"/api/cloud/user/add"
        :param params: type:dict，比如{"accountReference": "123456781"}
        :return:
        """
        nonce = "".join(random.choices(string.ascii_letters + string.digits, k=8))
        timestamp = str(int(time.time() * 1000))
        body = ""
        if method == "POST":
            body = json.dumps(params)
        signature = self.get_signature(method, path, nonce, timestamp, body)
        self.headers.update(
            {
                "API-Signature": signature,
                "API-TIMESTAMP": timestamp,
                "API-NONCE": nonce,
            }
        )

    def api_get_with_signature(self, path, params):
        """
        Desc：加签名的get请求
        :param path: 接口地址，比如"/api/cloud/user/add"
        :param params: type:dict，比如{"accountReference": "123456781"}
        :return:
        """
        self.add_headers_info("GET", path, params)
        url = "{}{}?{}".format(self.host, path, urllib.parse.urlencode(params))
        response = requests.get(url=url, headers=self.headers, verify=False)
        format_str = "{}\nRequest URL: {}\nRequest Headers: {}\nResponse: {}\nTrace-ID: {}"
        print(format_str.format("*" * 100, url, json.dumps(self.headers), response.text,response.headers.get("Trace-Id")))
        return response.json()

    def api_post_with_signature(self, path, params):
        """
        Desc：加签名的post请求
        :param path: 接口地址，比如"/api/cloud/user/add"
        :param params: type:dict，比如{"accountReference": "123456781"}
        :return:
        """
        self.add_headers_info("POST", path, params)
        url = "{}{}".format(self.host, path)
        response = requests.post(url=url, json=params, headers=self.headers, verify=False)
        format_str = "{}\nRequest URL: {}\nRequest Headers: {}\nRequest Params: {}\nResponse: {}\nTrace-ID: {}"
        print(format_str.format("*" * 100, url, json.dumps(self.headers), json.dumps(params), response.text, response.headers.get("Trace-Id")))
        return response.json()


if __name__ == "__main__":
    host = "https://antalphatest2.metalpha.fund"
    api_key = "zhang"
    private_key = """-----BEGIN RSA PRIVATE KEY-----
                        MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEAugXBzk9pBy8RjtDY
                        6sOnjXi7QNqUaZ8KtHxRI6eHliPitq779Gh2T9Hr2M7IDgmA4n6jIl1YdwQ89kvH
                        j345IQIDAQABAkEAiIGJArhLPjZQEBk51KzW233pC2Ja3lcTJ/bCJAPf/0/60kvx
                        55XmE7hb7jIOmBBjR6ldROkkgMvLW1J11qj1MQIhAPporqWg6y+twZ3xvW2y/hkI
                        /t2dBNqRyot6ncJ7pikDAiEAvi0MDAn9Fgjvqiu5wFXlrcYkCdYjURte4/jvGtqS
                        0gsCIDc5INLsExHXuuxPJJxtrfXtcu+CslBVeJqb9vCt/i3rAiEAotLQwLIApVAL
                        WohLZlhk6G5/xog3/qZPjSJCHZzMHdcCIQDalURPwoJM4eSAVBevLBHWNinjRrTn
                        Qe2LTM74dJtIQw==
                    -----END RSA PRIVATE KEY----- """

    api = OpenApiHttpRequest(host, api_key, private_key)
    # 获取充值地址
    # api.api_post_with_signature("/api/prime/antpool/v1/getAddress", {})
    # # # 进行提现
    # api.api_post_with_signature("/api/prime/antpool/v1/withdraw/applySingle",{"userId":11080481671553,
    #                                                                           "amount": "0.0022",
    #                                                                           "network":"SETH",
    #                                                                           "withdrawId":"10025101012",
    #                                                                           "toAddress":"0x1f60e356f120131f223e3596d8f5b5cb026f90fa",
    #                                                                           "currency":"SETH",
    #                                                                           "fromAddress":"0x1f60e356f120131f223e3596d8f5b5cb026f90fa"})
    # #  获取提现历史记录
    # res = api.api_post_with_signature("/api/prime/antpool/v1/withdraw/history",{"network":"SETH"}) # 10015101012
    #
    # t = 0
    # for i in res['result']['data']:
    #     print("\n")
    #     t+=1
    #     print(f"第{t}条提现记录")
    #     print("*"*100)
    #     print(i)